package com.vanysoft.business.system.dataDictionary.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.vanysoft.business.system.dataDictionary.dao.TSystemCodeMapper;
import com.vanysoft.business.system.dataDictionary.dao.TSystemDataTableMapper;
import com.vanysoft.business.system.dataDictionary.dao.TSystemDicMapper;
import com.vanysoft.business.system.dataDictionary.entity.FtlConfiger;
import com.vanysoft.business.system.dataDictionary.entity.TSystemCode;
import com.vanysoft.business.system.dataDictionary.entity.TSystemDataTable;
import com.vanysoft.business.system.dataDictionary.entity.TableConfiger;
import com.vanysoft.common.utils.freemark.FtlUtil;
import com.vanysoft.framework.exception.VanySoftBaseException;
import com.vanysoft.framework.messagesource.MessageCodeConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类名称：DataDictionaryService 类描述：数据字典列表 创建人：X 创建时间：2017年9月24日上午10:25:15 修改人：X
 * 修改时间：2017年9月24日 版本信息：@version 1.0 Copyright (c) 2017SharpClaw-版权所有 修改备注：
 */
@Service
@Transactional(readOnly = true)
public class DataDictionaryService {

    @Autowired
    private TSystemDataTableMapper tSystemDataTableMapper;

    @Autowired
    private TSystemDicMapper tSystemDicMapper;

    @Autowired
    private TSystemCodeMapper tSystemCodeMapper;

    /**
     * Function Name querySystemDataTable
     *
     * @param
     * @return
     * @throws VanySoftBaseException
     * @description 查询系统数据字典表数据 Modify History: Date Programmer Notes ---------
     * --------------- --------- 2017年9月24日上午10:28:39 X Initial
     * *********************************************************************
     */
    public List<Map<String, Object>> querySystemDataTable() throws VanySoftBaseException {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = tSystemDicMapper.queryTSystemDataTable();
        return list;
    }

    /**
     * Function Name queryTableConfiger
     *
     * @return
     * @throws VanySoftBaseException
     * @description 获取所有代码表的相关信息 Modify History: Date Programmer Notes ---------
     * --------------- --------- 2017年9月24日下午4:25:20 KING Initial
     * *********************************************************************
     */
    public List<Map<String, Object>> queryTableConfiger() throws VanySoftBaseException {

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = tSystemDataTableMapper.queryTableConfiger();
        return list;
    }

    /**
     * Function Name queryDictionaryList
     *
     * @return
     * @throws VanySoftBaseException
     * @description 查询代码信息列表 Modify History: Date Programmer Notes ---------
     * --------------- --------- 2017年9月24日下午6:18:25 X Initial
     * *********************************************************************
     */
    public Map<String, Object> queryDictionaryList(Integer pageSize, Integer pageNum, String searchValue,
                                                   String tableCode) throws VanySoftBaseException {
        Map<String, Object> operateLogs = new HashMap<String, Object>();
        // 分页工具
        Page<Map<String, Object>> page = new Page<>(pageNum, pageSize);
        List<TSystemCode> list = tSystemCodeMapper.queryDictionaryList(page, tableCode, searchValue);
        operateLogs.put("rows", list);
        operateLogs.put("total", page.getTotal());

        return operateLogs;
    }

    /**
     * Function Name delUpDictionary
     *
     * @return
     * @throws VanySoftBaseException
     * @description 系统登录API Modify History: Date Programmer Notes ---------
     * --------------- --------- 2017年9月24日下午6:58:06 KING Initial
     * *********************************************************************
     */
    public void InsertdelUpDictionary(String execSql) throws VanySoftBaseException {
        // tSystemDataTableMapper.InsertdelUpDictionary(execSql);
    }

    /**
     * Function Name isRepeat
     *
     * @return
     * @throws VanySoftBaseException
     * @description 判断是否主键重复 Modify History: Date Programmer Notes ---------
     * --------------- --------- 2017年9月24日下午7:05:12 X Initial
     * *********************************************************************
     */
    public boolean isRepeat(String tableCode, String field, String val) throws VanySoftBaseException {
        boolean isRepeat = false;
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = tSystemDataTableMapper.queryOneDictionary(tableCode, field, val);
        if (list.size() > 0) {
            isRepeat = true;
        }
        return isRepeat;
    }

    /**
     * Function Name editDictionary
     *
     * @param optType [1:add;2:update;3:delete]
     * @return
     * @throws VanySoftBaseException
     * @description 编辑代码信息 Modify History: Date Programmer Notes ---------
     * --------------- --------- 2017年10月11日下午11:48:44 X Initial
     * *********************************************************************
     */
    @Transactional
    public void editDictionary(String tableCode, String fields, String keys, String optType)
            throws VanySoftBaseException {
        String execSql = "select 1=1 ";
        if ("3".equalsIgnoreCase(optType)) {// 删除
            String[] keyArr = keys.split(";");
            StringBuffer delSql = new StringBuffer("delete from ");
            delSql.append(tableCode);
            delSql.append(" where 1=1 ");
            for (String keyStr : keyArr) {
                if (!"".equalsIgnoreCase(keyStr)) {
                    String[] colValue = keyStr.split(":");
                    delSql.append(" and " + colValue[0] + "= '");
                    delSql.append(colValue[1] + "'");
                }
            }
            execSql = delSql.toString();
            tSystemDataTableMapper.delDictionary(execSql);
        } else if ("2".equalsIgnoreCase(optType)) {
            String[] keyArr = keys.split(";");
            String[] fieldArr = fields.split(";");
            StringBuffer updateSql = new StringBuffer("update ");
            updateSql.append(tableCode);
            updateSql.append(" set ");
            for (String fieldStr : fieldArr) {
                if (!"".equalsIgnoreCase(fieldStr)) {
                    String[] colValue = fieldStr.split(":");
                    updateSql.append(colValue[0] + "='");
                    updateSql.append(colValue[1] + "',");
                }
            }
            updateSql.deleteCharAt(updateSql.length() - 1);
            updateSql.append("  where 1=1  ");
            for (String keyStr : keyArr) {
                if (!"".equalsIgnoreCase(keyStr)) {
                    String[] colValue = keyStr.split(":");
                    updateSql.append(" and " + colValue[0] + "= '");
                    updateSql.append(colValue[1] + "'");
                }
            }
            execSql = updateSql.toString();
            tSystemDataTableMapper.insertUpDictionary(execSql);
        } else if ("1".equalsIgnoreCase(optType)) {
            String[] fieldArr = fields.split(";");
            StringBuffer addSqlhead = new StringBuffer("insert into " + tableCode);
            StringBuffer addSqlbody = new StringBuffer("(");
            StringBuffer addSqlfooter = new StringBuffer("values(");
            for (String fieldStr : fieldArr) {
                if (!"".equalsIgnoreCase(fieldStr)) {
                    String[] colValue = fieldStr.split(":");
                    addSqlbody.append(colValue[0] + ",");
                    addSqlfooter.append("'" + colValue[1] + "',");
                }
            }
            addSqlbody.append("isAvaliable,");
            addSqlfooter.append("'1',");
            addSqlbody.deleteCharAt(addSqlbody.length() - 1);
            addSqlbody.append(")");
            addSqlfooter.deleteCharAt(addSqlfooter.length() - 1);
            addSqlfooter.append(")");
            execSql = addSqlhead.append(addSqlbody).append(addSqlfooter).toString();
            tSystemDataTableMapper.insertUpDictionary(execSql);
        }
    }

    /**
     * Function Name operaDictionary
     *
     * @param optType [1:add;2:update;3:delete]
     * @return
     * @throws VanySoftBaseException
     * @description 编辑代码信息 Modify History: Date Programmer Notes ---------
     * --------------- --------- 2017年10月11日下午11:48:44 X Initial
     * *********************************************************************
     */
    @Transactional
    public void operaDictionary(String optType, String code, String name, String type, String description) throws VanySoftBaseException {
        TSystemCode record = new TSystemCode();
        record.setCode(code);
        record.setName(name);
        record.setType(type);
        record.setDescription(description);
        record.setIsavaliable("1");
        if ("1".equalsIgnoreCase(optType)) {
            //检查code是否重复
            if (true == this.isCodeRepeat(type, code)) {
                throw new VanySoftBaseException(MessageCodeConstant.DicCodeException.RTN_CODE_DIC_CODE);
            }
            tSystemCodeMapper.insert(record);
        }
        if ("2".equalsIgnoreCase(optType)) {
            tSystemCodeMapper.updateByPrimaryKey(record);
        }
        if ("3".equalsIgnoreCase(optType)) {
            tSystemCodeMapper.delDictionary(type, code);
        }
    }

    /**
     * Function Name isCodeRepeat
     *
     * @return
     * @throws VanySoftBaseException
     * @description 判断是否主键重复 Modify History: Date Programmer Notes ---------
     * --------------- --------- 2017年9月24日下午7:05:12 X Initial
     * *********************************************************************
     */
    public boolean isCodeRepeat(String type, String code) throws VanySoftBaseException {
        boolean isRepeat = false;
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = tSystemCodeMapper.queryOneDictionary(type, code);
        if (list.size() > 0) {
            isRepeat = true;
        }
        return isRepeat;
    }

    /**
     * 生成HTML和JS方法
     * Function Name               createHtmlJs
     *
     * @return
     * @throws VanySoftBaseException
     * @description 系统登录API
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年10月13日上午1:09:45          KING          Initial
     * *********************************************************************
     */
    public boolean createHtmlJs() throws VanySoftBaseException, IOException {

        List<Map<String, Object>> listTables = tSystemDataTableMapper.queryTSystemDataTable();
        List<Map<String, Object>> listConfiger = tSystemDataTableMapper.queryTableConfiger();

        List<FtlConfiger> list = new ArrayList<FtlConfiger>();
        for (int i = 0; i < listTables.size(); i++) {
            FtlConfiger ftl = new FtlConfiger();
            TSystemDataTable table = (TSystemDataTable) listTables.get(i);
            ftl.setTableCode(table.getTableCode());
            ftl.setTableName(table.getTableName());
            List<TableConfiger> listObj = new ArrayList<TableConfiger>();
            for (int ii = 0; ii < listConfiger.size(); ii++) {
                TableConfiger obj = (TableConfiger) listConfiger.get(ii);
                if (obj.getTableName().equalsIgnoreCase(table.getTableCode())) {
                    listObj.add(obj);
                }
            }
            ftl.setTableConfigers(listObj);
            list.add(ftl);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("configer", list);
        boolean b = true;
        //classpath:/templates/system/dictionaryManagement/ftl/
        String templateName = "templates/system/dictionaryManagement/ftl/html.ftl";
        String filePath = "D:/";
        String fileName = "dictionaryManagement.html";

        FtlUtil.createFile(map, templateName, filePath, fileName);

        templateName = "templates/system/dictionaryManagement/ftl/js.ftl";
        filePath = "D:/";
        fileName = "dictionaryManagement.js";
        FtlUtil.createFile(map, templateName, filePath, fileName);
        return b;
    }

    /**
     * Function Name               isCreate
     *
     * @return
     * @throws VanySoftBaseException
     * @description 判断是否需要生成HTML和JS
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年10月13日上午1:11:29          KING          Initial
     * *********************************************************************
     */
    public boolean isCreate(String dicStr) throws VanySoftBaseException {
        String[] dics = {};
        if (!"".equalsIgnoreCase(dicStr)) {
            dics = dicStr.split(";");
        }
        boolean b = false;
        List<Map<String, Object>> list = tSystemDataTableMapper.queryTSystemDataTable();
        for (int i = 0; i < list.size(); i++) {
            TSystemDataTable obj = (TSystemDataTable) list.get(i);
            boolean haveTable = false;
            for (String tableCode : dics) {
                if (tableCode.equalsIgnoreCase(obj.getTableCode())) {
                    haveTable = true;
                }
            }
            if (!haveTable) {
                b = true;
                break;
            }
        }
        return b;
    }
}
